<template>
  <div class="p-3 flex">
    <div :style="{ width: tabsShow ? '35%' : '100%' }">
      <publicPageVue :json-obj="pageSetting" name="RoleMenuButton" :tables="tables" />
    </div>
    <div class="relative" :style="{ display: tabsShow ? 'block' : 'none', width: tabsShow ? '65%' : '' }">
      <el-tabs type="border-card" @tab-click="firstTab">
        <el-tab-pane class="p-3 flex" :label="translateTitle('Dams.DamsSystemManagement.菜单按钮权限')">
          <div style="width: 50%">
            <p class="p-3 font-bold text-center" style="background-color: '#F5F7FA'">菜单管理</p>
            <tree
              v-model="getTreeData"
              :checked-keys="getTreeData"
              :get-height="getHeight"
              :is-show-btn="true"
              :name="tables.name"
              :show-checkbox="true"
              :style="{ height: Number(getHeight) + 100 + 'px', 'overflow-y': 'auto' }"
              :tree-data="treeData"
              @checkedChange="checkedChange"
            />
            <template v-for="(v, i) in tableOtherList" :key="i">
              <el-button v-if="treeData.length != 0" type="primary" @click="common_event(v.FUNCTION_URI, 'main')">
                {{ v.BUTTON_NAME }}
              </el-button>
            </template>
          </div>
          <div v-loading="loadingCheckbox" style="width: 50%">
            <p class="p-3 font-bold text-center" style="background-color: '#F5F7FA'">按钮管理</p>
            <div v-if="buttonList.length != 0" class="grid-content bg-purple">
              <div :style="{ height: Number(getHeight) + 100 + 'px', 'overflow-y': 'auto' }">
                <div v-for="(item, index) of buttonList" :key="index">
                  <el-checkbox v-model="item.IS_CHECKED">{{ item.BUTTON_NAME }}</el-checkbox>
                </div>
              </div>
              <!-- <el-button type="primary" @click="save('chirden')">保存</el-button> -->
              <template v-for="(v, i) in tableOtherList" :key="i">
                <el-button type="primary" @click="common_event(v.FUNCTION_URI, 'chirden')">
                  {{ v.BUTTON_NAME }}
                </el-button>
              </template>
            </div>
            <div v-else class="grid-content bg-purple text-center text-gray-400 py-4">{{ translateTitle('Dams.DamsSystemManagement.暂无数据') }}</div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-dialog v-if="userDialog" v-model="userDialog" :title="translateTitle('Dams.DamsSystemManagement.用户信息')" width="50%">
      <el-tabs v-model="dialogActiveName" type="card" @tab-click="dialogClick">
        <el-tab-pane :label="translateTitle('Dams.DamsSystemManagement.未关联')" name="first">
          <Table
            ref="damsnotAssociatedBind"
            :btn-fix="false"
            :column-list="notAssociatedTablesColumn"
            :get-height="`300`"
            name="damsnotAssociatedBind"
            :style="{ height: `300px` }"
            :tables="notAssociatedTables"
          />
          <div class="text-center">
            <el-button size="small" type="primary" @click="roleBindUserSave">{{ translateTitle('Dams.DamsSystemManagement.保存') }}</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="translateTitle('Dams.DamsSystemManagement.已关联')" name="second">
          <Table
            :btn-fix="false"
            :column-list="userTablesColumn"
            :get-height="`300`"
            name="damsassociatedBind"
            :style="{ height: `300px` }"
            :tables="associatedTables"
          />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
  import { Mixin } from '@/common/minxin/Mixin'
  import { GFCD } from '@/utils/utils'
  import { arrayToTree } from '@/utils/tools'
  import publicPageVue from '../../components/publicPage.vue'
  import { getList } from '../../api/home'
  import Table from '../../components/table.vue'
  import Tree from '../../components/tree.vue'
  import debounce from 'lodash/debounce'
  import RoleMenuButton from '../../components/json/RoleMenuButton'
  import { translateTitle } from '@/utils/i18n'
  export default {
    name: 'RoleMenuButton',
    components: { publicPageVue, Tree, Table },
    mixins: [Mixin],
    data() {
      return {
        tableOtherList: [],
        clientHeight: 0,
        loadingTree: false,
        loadingCheckbox: false,
        defaultProps: {
          children: 'children',
          label: 'label',
        },
        treeData: [],

        tables: {
          tableList: [],
          count: 0,
          pageSize: 50,
          limit: 1,
          name: 'RoleMenuButton',
          operation: true, //true双击显示右侧不显示操作按钮
          myselfOperation: true, //自己单独的双击事件
          isNew: false,
          autoQuery: true, //第一次自动查询
        },
        notAssociatedTables: {
          tableList: [],
          count: 0,
          pageSize: 9999,
          limit: 1,
          name: 'damsnotAssociated',
          operation: true, //true双击显示右侧不显示操作按钮
          myselfOperation: true, //自己单独的双击事件
          isNew: false,
          width: '100',
          autoQuery: true, //第一次自动查询
          pagerOpen: true,
        },
        associatedTables: {
          tableList: [],
          count: 0,
          pageSize: 9999,
          limit: 1,
          name: 'damsassociated',
          operation: true, //true双击显示右侧不显示操作按钮
          myselfOperation: true, //自己单独的双击事件
          isNew: false,
          width: '100',
          autoQuery: true, //第一次自动查询
          pagerOpen: true,
        },
        userTables: {
          tableList: [],
          count: 0,
          pageSize: 50,
          limit: 1,
          name: 'damsMenuButtonPulicUser',
          operation: true, //true双击显示右侧不显示操作按钮
          myselfOperation: true, //自己单独的双击事件
          isNew: false,
          width: '100',
          autoQuery: true, //第一次自动查询
          pagerOpen: true,
        },
        userTablesColumn: [
          { label: translateTitle('Dams.DamsSystemManagement.用户名称'), porp: 'USER_NAME' },
          { label: translateTitle('Dams.DamsSystemManagement.登录账号'), porp: 'USER_ID' },
        ],
        tabsShow: false,
        pageSetting: {
          search: {
            form: {
              field: [],
            },
          },
        },
        url: '',
        buttonList: [], //按钮列表
        srcArr: [],
        getTreeData: [],
        ROLE_ID: '',
        postTreeData: [],
        unsubs: [],
        notAssociatedTablesColumn: [
          { type: 'checkbox' },
          { label: translateTitle('Dams.DamsSystemManagement.用户名称'), porp: 'USER_NAME' },
          { label: translateTitle('Dams.DamsSystemManagement.登录账号'), porp: 'USER_ID' },
        ],
        firstIndex: 0,
        userDialog: false,
        dialogActiveName: 'first',
      }
    },
    computed: {
      getHeight() {
        return `${this.clientHeight - 265}`
      },
    },
    unmounted() {
      this.unsubs.forEach((v) => {
        this.$unsub(v)
      })
    },
    created() {
      this.init()
    },
    methods: {
      translateTitle,
      async getUserList() {
        this.notAssociatedTables.tableList = []
        let url = GFCD('dams')
        let res = await getList(`${url.domain}${url.baseUrl}`, {
          data: JSON.stringify({ '#LIMIT#': 1, '#PAGE_SIZE#': 9999 }),
          method: 'sysUserServiceImpl.queryTable',
        })
        getList(this.url, {
          method: this.pageSetting['RoleMenuButton'].queryUser, //查询按钮
          data: JSON.stringify({
            '#LIMIT#': '1',
            '#PAGE_SIZE#': 999,
            ROLE_ID: this.ROLE_ID,
          }),
        }).then((r) => {
          this.associatedTables.tableList = r.data[this.pageSetting['RoleMenuButton'].queryUser].data
          res.data['sysUserServiceImpl.queryTable'].data.forEach((row) => {
            if (!this.associatedTables.tableList.find((el) => el.USER_ID == row.USER_ID)) {
              this.notAssociatedTables.tableList.push(row)
            }
          })
        })
      },
      roleBindUserSave() {
        this.$nextTick(() => {
          let checkboxList = this.$refs['damsnotAssociatedBind'].$refs['xTabledamsnotAssociated'].getCheckboxRecords().map((el) => el.USER_ID)
          let submitList = []
          checkboxList.forEach((row) => {
            submitList.push({
              USER_ID: row,
              USER_ROLE_ID: this.ROLE_ID,
            })
          })
          getList(this.url, {
            method: this.pageSetting['RoleMenuButton'].saveUserRole,
            data: JSON.stringify(submitList),
          }).then((res) => {
            if (res.code == '00000') {
              this.$message({
                message: res.msg,
                type: 'success',
              })
              this.treeShowData()
              this.getUserList()
            }
          })
        })
      },
      dialogClick() {
        this.getUserList()
      },
      roleUserBind() {
        this.userDialog = true
        this.getUserList()
      },
      common_event(event_name, type) {
        this[event_name](type)
      },
      save(type) {
        if (type == 'main') {
          let postObj = []
          this.postTreeData.forEach((item) => {
            postObj.push({
              MENU_CODE: item,
              ROLE_ID: this.ROLE_ID,
            })
          })
          if (postObj.length == 0) return this.$message({ type: 'error', message: translateTitle('Dams.DamsSystemManagement.请选择菜单后再保存') })
          this.loadingTree = true
          this.saveFuc(postObj, 'dams.roleManage.edit')
        } else if (type == 'chirden') {
          let postObj = []
          this.buttonList.forEach((item) => {
            if (item.IS_CHECKED) {
              postObj.push({
                BUTTON_ID: item.ID,
                ROLE_ID: this.ROLE_ID,
                MENU_CODE: this.MENU_CODE,
              })
            }
          })
          if (postObj.length == 0) {
            this.deleteBtn()
          } else {
            this.loadingCheckbox = true
            this.saveFuc(postObj, 'dams.roleButton.edit')
          }
        }
      },
      deleteBtn() {
        getList(this.url, {
          method: 'dams.roleButton.delete',
          data: JSON.stringify({ ROLE_ID: this.ROLE_ID, MENU_CODE: this.MENU_CODE }),
        }).then((res) => {
          if (res.code == '00000') {
            this.$message({
              message: res.msg,
              type: 'success',
            })
          }
        })
      },
      // 保存接口
      saveFuc(dataInfo, method) {
        getList(this.url, {
          method: method, //查询按钮
          data: JSON.stringify(dataInfo),
        }).then((res) => {
          if (res.code == '00000') {
            this.$baseMessage(res.msg, 'success')
            if (method == 'dams.roleManage.edit') {
              this.loadingTree = false
              this.query({ ROLE_ID: this.ROLE_ID, '#LIMIT#': 1, '#PAGE_SIZE#': 9999 }, 'dams.role.menu.query')
            } else if (method == 'dams.roleButton.edit') {
              this.loadingCheckbox = false
              this.query({ MENU_CODE: this.MENU_CODE, ROLE_ID: this.ROLE_ID, '#LIMIT#': 1, '#PAGE_SIZE#': 50 }, 'dams.menu.button.query')
            }
          }
        })
      },
      windowResize: debounce(function () {
        console.log('document.documentElement.clientHeight', document.documentElement.clientHeight)
        this.clientHeight = document.documentElement.clientHeight
      }, 100),
      init() {
        this.configSetting = GFCD('dams')
        let menuBtns = this.$store.getters['user/menuBtns']
        menuBtns.forEach((row) => {
          if (this.$route.name.indexOf(row.MENU_CODE) > -1 && row.SHOW_POSTION == 'other') {
            this.tableOtherList.push(row)
          }
        })
        console.log('tableOtherList', this.tableOtherList)
        // this.nowJsonData().then((data) => {
        this.pageSetting = RoleMenuButton
        // })
        this.url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
        this.windowResize()
        this.eventInit()
      },
      firstTab(e) {
        this.firstIndex = e.index
        this.treeShowData()
      },
      treeShowData() {
        if (this.firstIndex == 0) {
          this.loadingTree = true
          // 主权限
          this.treeData = []
          this.padTreeData = []
          this.query({ ROLE_ID: this.ROLE_ID, '#LIMIT#': 1, '#PAGE_SIZE#': 9999 }, 'dams.role.menu.query')
        } else {
          getList(this.url, {
            method: this.pageSetting['RoleMenuButton'].queryUser, //查询按钮
            data: JSON.stringify({
              '#LIMIT#': '1',
              '#PAGE_SIZE#': 999,
              ROLE_ID: this.ROLE_ID,
            }),
          }).then((res) => {
            console.log(res)
            this.userTables.tableList = res.data[this.pageSetting['RoleMenuButton'].queryUser].data
            this.userTables.count = res.data[this.pageSetting['RoleMenuButton'].queryUser].count
          })
        }
      },
      eventInit() {
        this.$sub(`RoleMenuButton_myselfOperation`, (page_arr) => {
          this.tabsShow = true
          this.ROLE_ID = page_arr[0].ID
          this.buttonList = []
          this.treeShowData()
        })
        this.unsubs.push('RoleMenuButton_myselfOperation')
        this.$sub(`RoleMenuButton_nodeClick`, (page_arr) => {
          this.loadingCheckbox = true
          //子权限
          this.MENU_CODE = page_arr[0].id
          let obj2 = { MENU_CODE: page_arr[0].id, ROLE_ID: this.ROLE_ID, '#LIMIT#': 1, '#PAGE_SIZE#': 50 }
          this.query(obj2, 'dams.menu.button.query')
        })
        this.unsubs.push('RoleMenuButton_nodeClick')
      },
      checkedChange(data) {
        let _arr = []
        data['multiples'].forEach((v) => {
          _arr.push(v.id, v.pid)
        })
        this.postTreeData = [...new Set(_arr.filter(Boolean))]
      },
      // 查询接口
      query(dataInfo, method) {
        getList(this.url, {
          method: method, //查询按钮
          data: JSON.stringify(dataInfo),
        }).then((res) => {
          //子权限
          if (method == 'dams.menu.button.query') {
            this.buttonList = res.data[method].data
            this.buttonList.forEach((it) => {
              it.IS_CHECKED == 'Y' ? (it.IS_CHECKED = true) : (it.IS_CHECKED = false)
            })

            this.loadingCheckbox = false
            // 主权限
          } else if (method == 'dams.role.menu.query') {
            let _arr = []
            let _checkedData = []
            let allChecked = []
            res.data[method].data.forEach((item) => {
              if (item.IS_CHECKED == 'Y' && item.PID != '') {
                _checkedData.push(item.ID)
              }
              if (item.IS_CHECKED == 'Y') {
                allChecked.push(item.ID)
              }
              _arr.push({
                id: item.ID,
                name: item.MENU_NAME,
                pid: item.PID,
                children: [],
                label: item.MENU_NAME,
              })
            })

            this.loadingTree = false
            this.treeData = arrayToTree(_arr, 'id', 'pid', 'children')

            this.treeData.forEach((v) => {
              if (v.children.length == 0) {
                // allChecked
                allChecked.find((it) => {
                  if (v.id == it) {
                    _checkedData.push(v.id)
                  }
                })
              }
            })
            this.getTreeData = _checkedData
          }
        })
      },
    },
  }
</script>

<style lang="scss" scoped></style>
